package com.exercise.widgets.recyclerview.table.adapter

import android.view.LayoutInflater
import android.view.View
import android.widget.LinearLayout
import android.widget.TextView
import com.chad.library.adapter.base.BaseQuickAdapter
import com.chad.library.adapter.base.viewholder.BaseViewHolder
import com.exercise.widgets.R
import com.exercise.widgets.recyclerview.table.model.TableEntity

class TableAdapter : BaseQuickAdapter<TableEntity, BaseViewHolder>(
    layoutResId = R.layout.activity_table_row
) {
    private val inflater by lazy {
        LayoutInflater.from(context)
    }

    override fun convert(holder: BaseViewHolder, item: TableEntity) {
        val column1 = holder.getView<LinearLayout>(R.id.c1)
        column1.removeAllViews()
        val (billNo, list) = item
        billNo?.let {
            createColumn1View(it)
        }?.let {
            column1.addView(it)
        }

        val column2 = holder.getView<LinearLayout>(R.id.c2)
        column2.removeAllViews()
        list?.map {
            createColumn1View(it.fzNo ?: "")
        }?.forEach {
            column2.addView(it)
        }

        val column3 = holder.getView<LinearLayout>(R.id.c3)
        column3.removeAllViews()
        list?.map {
            createColumn1View("${it.fzCount ?: 0}")
        }?.forEach {
            column3.addView(it)
        }
        val column4 = holder.getView<LinearLayout>(R.id.c4)
        column4.removeAllViews()
        list?.flatMap {
            it.list ?: emptyList()
        }?.map {
            createColumn1View(it.pigstyNo ?: "")
        }?.forEach {
            column4.addView(it)
        }
    }

    private fun createColumn1View(billNo: String): View {
        val itemView = inflater.inflate(R.layout.activity_table_item, null)as TextView
        itemView.text = billNo
        itemView.layoutParams = LinearLayout.LayoutParams(
            LinearLayout.LayoutParams.MATCH_PARENT,
            0,
        ).apply {
            weight = 1f
        }
        return itemView
    }
}